<form action="" class="form-horizontal" role="form">

  <div id="show-fields" class="form-group">
		<label class="col-sm-2 control-label">是否对普通用户开放</label>
		<div class="col-sm-3">
			<label><input type="checkbox" name="qr_config[opening]" value="1" {$qrConfig['opening']?'checked="checked"':''}/>是</label>
		</div>
  </div>

  <div id="show-fields" class="form-group">
		<label class="col-sm-2 control-label">显示字段</label>
		<div class="col-sm-3">
			<label><input type="checkbox" name="qr_config[fields][qrcode][enable]" field-name="qrcode" value="1" {$qrConfig['fields']['qrcode']['enable']?'checked="checked"':''}/>二维码</label>
			<label><input type="checkbox" name="qr_config[fields][face][enable]" field-name="face" value="1" {$qrConfig['fields']['face']['enable']?'checked="checked"':''}/>头像</label>
			<label><input type="checkbox" name="qr_config[fields][nickname][enable]" field-name="nickname" value="1" {$qrConfig['fields']['nickname']['enable']?'checked="checked"':''}/>昵称</label>
		</div>
  </div>
  
  <div class="form-group">
		<label class="col-sm-2 control-label">二维码底图</label>
		<div class="col-sm-10">
	      <input type="text" class="form-control margin-bottom" name="qr_config[img]" id="img" placeholder="请上传图标" value="{$qrConfig.img}"> 
	      <div>
	      	<span class="btn btn-primary" id="upload-image">上传图片</span>
	      </div>
	      <div id="img-place" class="img-place" style="<empty name='qrConfig.img'>display:none;</empty>">
	      	<img id="img-source" src="{$qrConfig.img}" />
	      </div>
		</div>
  </div>
  
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-8">
    	<div id="hidden-data">
    		
    	</div>
    	<a class="btn btn-default" onclick="javascript:history.go(-1)">返回上页</a>
		<a class="btn btn-default" onclick="self.location=document.referrer">返回上页并刷新</a>
      	<button type="submit" class="btn btn-primary submit" data-loading-txt="提交中，请稍后……" data-ajax-url="__CONTROLLER__/qrcodePost" call-action-before="onBeforeSubmit">保存更改</button>
    </div>
  </div>
  
</form>

<style type="text/css">
#face { cursor: move; position: absolute; }
#box { cursor: move; position: absolute; background-image:url(); background-size: cover; background-color: #FFF; border: 1px solid #CCCCCC;  -webkit-box-shadow: 10px 10px 25px #ccc;-moz-box-shadow: 10px 10px 25px #ccc;box-shadow: 10px 10px 25px #ccc;}
#coor { width: 10px; height: 10px; overflow: hidden; cursor: se-resize; position: absolute; right: 0; bottom: 0; background-color: #09C; }
</style>

<style type="text/css">
.img-place {
	height: 45em;
	border: 1px solid;
	overflow: auto;
	position: relative;
}
.dragable-block {
	display: block;
	position: absolute;
	background: #DD4D00;
	opacity: 0.8;
}
</style>

<link rel="stylesheet" type="text/css" href="__PUBLIC__/Style/Common/bigcolorpicker/jquery.bigcolorpicker.css">
<script type="text/javascript" src="__PUBLIC__/Style/Common/bigcolorpicker/jquery.bigcolorpicker.min.js"></script>
<!-- uploadify -->
<link rel="stylesheet" href="__PUBLIC__/Style/Common/uploadify/uploadify.css">
<script type="text/javascript" src="__PUBLIC__/Style/Common/uploadify/jquery.uploadify.min.js?{:rand(0,9999)}"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">

  function toArray( data, level, path, result ) {
    for(var o in data) {
      var p = path + (level? "["+o+"]" : o);
      if (Object.prototype.toString.call(data[o]) === '[object Array]' || Object.prototype.toString.call(data[o]) === '[object Object]') {
        this.toArray(data[o],1 + level, p, result);
      } else {
          Object.prototype.toString.call(result) === '[object Object]' && (result[p] = data[o]);
          Object.prototype.toString.call(result) === '[object Array]' && result.push( p + "=" + data[o] );
        }
    };
    return result;
  }

  $("#upload-image").uploadify({
    'multi'            :  true,
    'buttonClass'      :  'margin-bottom',
    'fileSizeLimit'    :   '200kb',
    'buttonText'       :  '上传图片',
    'fileTypeDesc'     :   'Image Files',
    'fileTypeExts'     :   '*.jpg; *.png',
    'swf'              :   '__PUBLIC__/Style/Common/uploadify/uploadify.swf',
    'uploader'         :   '__MODULE__/Upload/uploadOne',
    'onUploadStart'    :  function(){},
    'onUploadSuccess'  : function( data, res ) {
      var url = eval("(" + res + ")").extra.url;
      if ( data.error != 0) {
    	  $("#img").val( url );  
    	  $("#img-source").attr("src", url);
    	  $(".img-place").show();
      }
    }
  });
  
  var fieldsConfig = {$fieldsConfig},  // 字段固定基础设置
  	  config = {$qrConfigJson};
  
  
  $(function() {
	  
		$(document).mousemove(function(e) {
			if (!!this.move) {
				var callback = document.call_down || function() {};
				callback.call(this, e);
			}
		}).mouseup(function(e) {
			if ( !!this.move ) {
				var callback = document.call_up || function(){};
				callback.call(this, e);
				$.extend(this, {
					'move': false,
					'move_target': null,
					'call_down': false,
					'call_up': false
				});
			}
		});

		function switchBlock( field, state ) {
			var cfg = fieldsConfig[field],
				id = cfg['id'];
			var block = $("#img-place").find('#'+id);
			if ( state ) {
				if ( block.size() ) {
					block.show();
				} else {
					var rect = getDefaultRect(field);
					addBlock(cfg['id'], rect, cfg['type']);
				}
			} else {
				block.size() && block.hide();
			}
		}
		
		function addBlock( id, rect, type ) {
			type = type || 0;
	      	var html = "<div id=\""+id+"\" class=\"dragable-block\"><div id=\"coor\"></div></div>";
	      	$("#img-place").append(html);
			
			var $box = $('#'+id).draggable({ scroll:false }).on('mousedown', '#coor', function(e) {
				
			    var posix = {
			            'w': $box.width(), 
			            'h': $box.height(), 
			            'x': e.pageX, 
			            'y': e.pageY
			        };
			    
			    $.extend(document, {'move': true, 'call_down': function(e) {
			        $box.css({
			            'width': Math.max(30, e.pageX - posix.x + posix.w),
			            'height': !type?Math.max(30, e.pageY - posix.y + posix.h):Math.max(30, e.pageX - posix.x + posix.w)
			        });
			    }});
			    
			    return false;
			});
			
			$box.css({
				'width' : rect.w,
				'height' : rect.h,
				'left' : rect.x*1,
				'top' : rect.y*1
			});
		}
		
		function getDefaultRect(field) {
			var rect = {};
			var cfg = fieldsConfig[field];
			if ( cfg['w'] && cfg['h'] ) {
				rect['w'] = cfg['w'];
				rect['h'] = cfg['h'];
			} else {
				rect['w'] = 100;
				rect['h'] = 30;
			}
			rect['x'] = rect['y'] = 0;
			return rect;
		}
		
		function init() {
			$("#show-fields input[type='checkbox']").click(function() {
				switchBlock( $(this).attr('field-name'), $(this).is(":checked"));
			});
			
			for( var field in config['fields'] ) {
				var cfg = fieldsConfig[field],
					rect = config['fields'][field]['rect'] || {};
				if ( !(rect['w'] && rect['h']) ) {
					rect = getDefaultRect(field);
				}
				addBlock(cfg['id'], rect, cfg['type']);
			}
		}
		
		window.getAllBlock = function() {
			var f = {};
			for( var field in fieldsConfig ) {
				var cfg = fieldsConfig[field];
				var block = $("#"+cfg['id']);
				if ( block.size() > 0 && block.css('display') != 'none' ) {
					f[field] = {};
					f[field]['rect'] = {
						'x': block.get(0).offsetLeft,
						'y': block.get(0).offsetTop,
						'w': block.width(),
						'h': block.height()
					};
				}
			}
			return f;
		};
		
		init();
		
		window.onBeforeSubmit = function() {
			var data = {'qr_config':{'fields': {}}};
			data['qr_config']['fields'] = getAllBlock();
			var d = toArray(data, 0, "", {});
			var fieldsHtml = "";
			for( var o in d ) {
				fieldsHtml += "<input type=\"hidden\" name=\""+o+"\" value=\""+d[o]+"\" >";
			}
			$("#hidden-data").html(fieldsHtml);
		}
		
	});
  
</script>